/**
 * http://truben.no/latex/bibtex/
 */

// List of all entry types
var entrytypes = [ 'article', 'book', 'booklet', 'conference', 'inbook',
                'incollections', 'inproceedings', 'manual', 'masterthesis', 'misc',
                'phdthesis', 'proceedings', 'techreport', 'unpublished' ];

var required = []; // Required fields
var optional = []; // Optional fields
var selectedtype;
var entryvalues = [];

required['article'] = [ 'author', 'title', 'journal', 'year' ];
optional['article'] = [ 'volume', 'number', 'pages', 'month', 'note' ];

required['book'] = [ 'author', 'title', 'publisher', 'year'];
optional['book'] = [ 'volume', 'series', 'address', 'edition', 'month',
                'note', 'pages', 'isbn' ];

required['booklet'] = [ 'title' ];
optional['booklet'] = [ 'author', 'howpublished', 'address', 'month',
                'year', 'note' ];

required['conference'] = [ 'author', 'title', 'booktitle', 'year' ];
optional['conference'] = [ 'editor', 'pages', 'organization', 'publisher',
                'address', 'month', 'note' ];

required['inbook'] = [ 'author', 'title', 'chapter', 'publisher', 'year' ];
optional['inbook'] = [ 'volume', 'series', 'address', 'edition', 'month',
                'note' ];

required['incollections'] = [ 'author', 'title', 'booktitle', 'year' ];
optional['incollections'] = [ 'editor', 'pages', 'organization',
                'publisher', 'address', 'month', 'note' ];

required['inproceedings'] = [ 'author', 'title', 'booktitle', 'year' ];
optional['inproceedings'] = [ 'editor', 'pages', 'organization',
                'publisher', 'address', 'month', 'note' ];

required['manual'] = [ 'title' ];
optional['manual'] = [ 'author', 'organization', 'address', 'edition',
                'month', 'year', 'note' ];

required['masterthesis'] = [ 'author', 'title', 'school', 'year' ];
optional['masterthesis'] = [ 'address', 'month', 'note' ];

required['misc'] = [];
optional['misc'] = [ 'author', 'title', 'howpublished', 'month', 'year',
                'note' ];

required['phdthesis'] = [ 'author', 'title', 'school', 'year' ];
optional['phdthesis'] = [ 'address', 'month', 'note' ];

required['proceedings'] = [ 'title', 'year' ];
optional['proceedings'] = [ 'editor', 'publisher', 'organization',
                'address', 'month', 'note' ];

required['techreport'] = [ 'author', 'title', 'institution', 'year' ];
optional['techreport'] = [ 'type', 'number', 'address', 'month', 'note' ];

required['unpublished'] = [ 'author', 'title', 'note' ];
optional['unpublished'] = [ 'month', 'year' ];


String.prototype.replaceAll = function (replaceThis, withThis) {
   var re = new RegExp(replaceThis,"g"); 
   return this.replace(re, withThis);
};


function createTable(array, isRequired) {
	var output = '<table>';
	for ( var i = 0; i < array.length; i++) {
                var value = typeof entryvalues[array[i]] == 'undefined' ? '' : 'value = "' + entryvalues[array[i]] + '"';
		output += '<tr>';
		output += '<td class="first"><label for="' + array[i] + '" style = "text-transform: capitalize" >' + array[i]
				+ '</label></td> ';
		output += '<td class="last"><input onchange="generateCode()" '+ isRequired +' class="value" id="' + array[i] + '" ' + value + '/></td>';
		output += '</tr>';
	}
	output += '</table>';
	return output;
}

function selectText(element) {
	$(element).focus();
	$(element).select();
}


function createExtraSpaces(word, wlength) {
	var w = word.length;
	for(var i = 0; i < wlength - w;i++)
		word += " ";
	return word;
}

function escapeChars(sentence) {
	
	
	var escape = new Array(); // Escape chars
	
	escape['\\\\'] = "\\\\";
	escape['&']  = "\\&";
	escape['\\$']  = "\\$";
	escape['"']  = '{"}';
	escape['<']  = '$\\langle$';
	escape['>']  = '$\\rangle$';
	
	for(var i in escape) {
		sentence = sentence.replaceAll(i, escape[i]);
	}
	return sentence;
}

function generateCode() {

	var output = '@' + $('#entry').val() + '{' + $('#key').val() + ',\n';
        var initialoutput = output;
	var done = false;
	var stuffVal = $('.value').val() || [];
	var stuffId = $('.value').attr('id') || [];

	var maxlen = 0;

	// Find maximum length
	$('.value').each(
			function() {if ($(this).val() != "") {
				if($(this).attr('id').length > maxlen)
					maxlen = $(this).attr('id').length;
			}}
	);

	$('.value').each(
			function() {
				if ($(this).val() != "") {
					done = true;
					output += '  ' + createExtraSpaces($(this).attr('id'),maxlen+1) + '= ' + $('#startsign').val()
							+ escapeChars($(this).val()) + $('#stopsign').val() + ',\n';
				}
			}
	);


        if (output == initialoutput && $('#key').val() == "")
            output = "";
        else {
            if (done == true)
                output = output.substring(0, output.length - 2);
            output += "\n}";
        }
        
	$('#research_citation').text(output);
}

//function toggleOptions() {
//	$('#options').slideToggle('slow');
//	$('#showHideOptions').text($('#showHideOptions').text() == 'Show Options' ? 'Hide Options' : 'Show Options');
//}

function toggleOptionalFields() {
	$('#optional_fields').slideToggle('slow');
	$('#hide_show_opt_fields').text($('#hide_show_opt_fields').text() == 'show' ? 'hide' : 'show');
}

function buildUI() {

//	$('#ui').slideUp("fast");

	selected = $('#entry').val();

	if (selected == null) {
            if (selectedtype == null)
                selected = 'article';
            else
                selected = selectedtype;
        }
		

	var output = "";

	output += '<h5>Type of Document</h5>';

	output += '<select id="entry" onchange="buildUI()">';

	for ( var i = 0; i < entrytypes.length; i++) {
		if (entrytypes[i] == selected) {
			output += '<option value="' + entrytypes[i] + '" selected>'
					+ entrytypes[i] + '</selected>';
		} else {
			output += '<option value="' + entrytypes[i] + '">' + entrytypes[i]
					+ '</selected>';
		}
	}

	output += '</select>';

	output += '<h5>Cite Key</h5>';

        var cite = typeof entryvalues['cite'] == 'undefined' ? "" : entryvalues['cite'];
	output += '<input id="key" value = "' + cite + '" />';

	output += '<h5>Required Fields of ' + selected + '</h5>';
        output += '<p>(separate each author with " and ")</p>';
	output += createTable(required[selected], '');

	output += '<h5>Optional Fields  <span id="hide_show_opt_fields" onclick="toggleOptionalFields()" class="link-div">show</span></h5>';

        output += '<div id = "optional_fields" style="display: none">';
	output += createTable(optional[selected], '');
        output += '</div>';

	$("#bibtex_fields").html(output);

	setTimeout( function() {
		$("#bibtex_fields").slideDown("fast");
	}, 300);

	$('input').bind("keypress keyup change mousedown", generateCode);

	generateCode();

}

function validateBibtex() {
    var errMsg = [];
    var selected = $('#entry').val();

    if (selected == null)
        return errMsg;

    for (var i=0; i < required[selected].length; i++) {
        if ($('#' + required[selected][i]).val() == "") {
            errMsg[i] = required[selected][i];
        }
    }

    return errMsg;
}

